/*  
     PlAr is Platform Arena: a 2D multiplayer shooting game
     Copyright (C) 2009 Ragagnin Antonio <spocchio@gmail.com>
     
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package plar.demo;

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JOptionPane;
import java.util.Calendar;
import plar.ClientServer.Client;
import plar.ClientServer.ShownElement;
import plar.core.Common;

/**
 * 
 * @author spok
 */
public class client extends javax.swing.JFrame {

    /**
     * @param args
     *            the command line arguments
     */
    public ArrayList<String> premuti;
    public static Client c;

    /** Creates new form UI2 */
    public GamePanel gameFrame1;
    
    public static void main(String args[]) throws IOException {

        int port = Common.port;
       Common.info(Common.product+" ver:"+Common.version);
       Common.info("Created by "+Common.author+" "+Common.copyright);
       Common.info(Common.license);
        String s = JOptionPane.showInputDialog(null, "Insert PlAr server: ");
        c = new Client();
        String welcome;
        try {
            welcome = c.connect(s, port);
        } catch (ClassNotFoundException e) {
            welcome = null;
            e.printStackTrace();
        }
    
        if (welcome != null) {
            JOptionPane.showMessageDialog(null, "Server says: " + welcome,"Plar", JOptionPane.INFORMATION_MESSAGE);
    
            String name = "."+JOptionPane.showInputDialog(null, "Choose username: ");
            String type = "."+JOptionPane.showInputDialog(null, "Select player type: [kitty/queen/squeak] ");

            if(c.getClient())   {
                c.setPlayer(name, type);
                c.dropClient();
            }

            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() { new client().setVisible(true);  }});
            }
    }





    public client() {
        initComponents();
        btnInitializeMouseClicked();
    }


    private void btnInitializeMouseClicked() {// GEN-FIRST:event_btnInitializeMouseClicked
        premuti = new ArrayList<String>();

        class autoupdateGUI extends Thread {

            public void run() {
                        try {
                            long a,b,delay;
                    
                                int i=0;
                            while (c.isConnected()) {

                                a = Calendar.getInstance().getTimeInMillis();
                                gameFrame1.viewOutput(c);
                               
                     //           if(i%2==0)
                                       
                  
                   // i=0;
                
               // i++;
                
                 b =  Calendar.getInstance().getTimeInMillis();
                                delay = b-a;
                                if(delay<60)  Thread.sleep(60-delay);

                                //Common.info("A:"+a+" B:"+b+" DEL:"+delay);
                                gameFrame1.delay =(int)delay;
                                
                            }
                        }catch (InterruptedException e) {e.printStackTrace();}
                        JOptionPane.showMessageDialog(null, "Connection closed:\n"+c.error);
                        System.exit(0);
                }
        }

        class autoSEND extends Thread {
            
            public void run() {
                                            String lastPremuti = premuti.toString();
                        try {

                          while(true)
                    {
						//Common.info("lastPremuti:"+lastPremuti+" premuti:"+premuti.toString());
                        if(!lastPremuti.equals(premuti.toString()))
                          if(c.getClient())
                          {
							  
                    c.sendInput(premuti);
                    c.dropClient();
                     Common.info("sending:" + premuti);
                          lastPremuti = premuti.toString();
                }
                
					if(premuti.contains("fire")) premuti.remove("fire");
					//premuti.clear();
					Thread.sleep(23);
               
                    }
                  
                
            
                        }catch (InterruptedException e) {e.printStackTrace();}
                        JOptionPane.showMessageDialog(null, "Connection closed:\n"+c.error);
                        System.exit(0);
                }
        }

        Thread tGUI = new autoupdateGUI();
        tGUI.setName("Thread gui");
        System.out.println("Thread in esecuzione: " + tGUI);
        tGUI.start();
        Thread tSEND = new autoSEND();
        tSEND.start();
        
        gameFrame1.setVisible(true);
        gameFrame1.requestFocus();
    }

    private void initComponents() {

        this.addMouseListener(new java.awt.event.MouseListener()
        {
        public void mouseClicked(MouseEvent e) {requestFocus();}
        public void mouseEntered(MouseEvent e) {requestFocus(); Common.info("focus me!");}
            public void mouseExited(MouseEvent e) {}
            public void mousePressed(MouseEvent e){
                
                double x = e.getX();
                double y = c.resolution.y-e.getY();
                x-=c.resolution.x/2;
                y-=c.resolution.y/2-30;
                double mod = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
                x/=mod;
                y/=mod;

                //x/=c.resolution.x/2;
                //y/=c.resolution.y/2;
                
                double atan = -(y/x);
                double theta = Math.atan2(y,x)/Math.PI;
        
            if(!premuti.contains("fire")) {
                premuti.add("fire");
                 Common.info("fire!");;
			 }
            //    if(c.getClient())
                    {
                            
        //      Common.info("x: "+x+" y:"+y+"theta: "+theta+" atan:"+atan);;
                  //      
                        c.setDirection(x,-y);
                    //    c.sendInput(premuti);
                    //    c.dropClient();
                    }
                   
                }
            public void mouseReleased(MouseEvent e) {}
        });
        
        gameFrame1 = new GamePanel(c.resolution);
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        gameFrame1.setBackground(new java.awt.Color(20, 20, 20));
         this.getContentPane().add(BorderLayout.CENTER, gameFrame1);
        this.addKeyListener(new java.awt.event.KeyListener() {

            @Override
            public void keyPressed(KeyEvent e) {
            //if (e.isAltDown() && !premuti.contains("special"))
                if ((e.getKeyCode() == KeyEvent.VK_C ))
                {
                String chat = JOptionPane.showInputDialog(null, "Chat");
                    if(c.getClient())
                    {
                        c.chat(chat);
                        c.dropClient();
                    }
                }
        
            //      premuti.add("special");
                  if (e.getKeyCode() == KeyEvent.VK_1 && !premuti.contains("1"))  premuti.add("1");
				if (e.getKeyCode() == KeyEvent.VK_2 && !premuti.contains("2"))  premuti.add("2");
				if (e.getKeyCode() == KeyEvent.VK_3 && !premuti.contains("3"))  premuti.add("3");
				
                if ((e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_UP|| e.getKeyCode() == KeyEvent.VK_W)&& !premuti.contains("jump"))
                    premuti.add("jump");
                if ((e.getKeyCode() == KeyEvent.VK_RIGHT  || e.getKeyCode() == KeyEvent.VK_D)&& !premuti.contains("right"))
                    premuti.add("right");
                if ((e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A)&& !premuti.contains("left"))
                    premuti.add("left");
               
                  

            }

            @Override
            public void keyReleased(KeyEvent e) {
                //if (e.isAltDown())
                //  premuti.remove("special");
               if (e.getKeyCode() == KeyEvent.VK_1) premuti.remove("1");
				if (e.getKeyCode() == KeyEvent.VK_2) premuti.remove("2");
				if (e.getKeyCode() == KeyEvent.VK_3) premuti.remove("3");
                if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_SPACE|| e.getKeyCode() == KeyEvent.VK_W)
                    premuti.remove("jump");
                if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D)
                    premuti.remove("right");
                if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A)
                    premuti.remove("left");


               
          

            }

            @Override
            public void keyTyped(KeyEvent e) {
            }
        });
        
        pack();
        this.setSize(c.resolution.x,c.resolution.y+60);
        this.validate();

        
    }

}
